#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

//创建节点
ListNode* Buynode(ListValType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (node == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	node->val = x;
	node->next = node;
	node->prev = node;
	return node;
}

//双向链表的初始化
ListNode* ListInit()
{
	//创建一个头节点（哨兵位）
	ListNode* phead = Buynode(-1);
	return phead;
}

//双向链表的打印
void ListPrint(ListNode* phead)
{
	assert(phead);

	ListNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->val);
		pcur = pcur->next;
	}
	printf("\n");
}

//尾插
void ListPushBack(ListNode* phead,ListValType x)
{
	assert(phead);//判断该双向链表是否有效

	ListNode* newnode = Buynode(x);
	//phead head->prev newnode
	newnode->prev = phead->prev;
	newnode->next = phead;

	phead->prev->next = newnode;
	phead->prev = newnode;
}

//头插
void ListPushFront(ListNode* phead, ListValType x)
{
	assert(phead);

	ListNode* newnode = Buynode(x);
	//phead newnode phead->next
	newnode->next = phead->next;
	newnode->prev = phead;

	phead->next->prev = newnode;
	phead->next = newnode;
}

//尾删
void ListPopBack(ListNode* phead)
{
	assert(phead && phead->next != phead);//删除的链表必须是有效链表，即不能只包含头节点

	ListNode* del = phead->prev;//要删除的尾节点

	//phead del->prev del
	del->prev->next = phead;
	phead->prev = del->prev;

	free(del);
	del = NULL;
}

//头删
void ListPopFront(ListNode* phead)
{
	assert(phead && phead->next != phead);

	ListNode* del = phead->next;

	//phead del del->next
	del->prev = phead;
	phead->next = del->next;

	free(del);
	del = NULL;
}

//查找节点
ListNode* Find(ListNode* phead, ListValType x)
{
	ListNode* pcur = phead->next;
	//遍历链表
	while (pcur != phead)
	{
		if (pcur->val == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

//在指定位置之后插入数据
void ListInsert(ListNode* pos, ListValType x)
{
	assert(pos);
	ListNode* newnode = Buynode(x);
	//pos newnode pos->next
	newnode->next = pos->next;
	newnode->prev = pos;

	pos->next->prev = newnode;
	pos->next = newnode;
}

//删除pos节点
void ListErase(ListNode* pos)
{
	assert(pos);
	//pos->prev pos pos->next
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;

	free(pos);
	pos = NULL;
}

//链表的销毁
void ListDestory(ListNode* phead)
{
	assert(phead);
	ListNode* pcur = phead->next;
	ListNode* next = pcur->next;
	while (pcur != phead)
	{
		free(pcur);
		pcur = next;
		next = pcur->next;
	}
	//到这里，所有的有效节点已经删除了，现在只需要删除头节点
	free(phead);
	phead = NULL;
}